//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using SPUserPoll.Business.Components;
using Microsoft.SharePoint.WebPartPages;
using System.Text;
using Microsoft.SharePoint.Utilities;

namespace SPUserPoll.Presentation.WebParts.UserControls
{
    public partial class PollDisplayControl : System.Web.UI.UserControl
    {

        private Control _pollingWebpart = null;

        /// <summary>
        /// Access to the polling webpart
        /// </summary>
        private PollDisplayWebPart PollingWebPart
        {
            get
            {
                if (_pollingWebpart == null)
                    _pollingWebpart = this;

                if (_pollingWebpart.GetType() != typeof(PollDisplayWebPart))
                {
                    _pollingWebpart = this;
                    while (_pollingWebpart.GetType() != typeof(PollDisplayWebPart))
                    {
                        _pollingWebpart = _pollingWebpart.Parent;
                    }
                }
                return _pollingWebpart as PollDisplayWebPart;
            }
        }


        /// <summary>
        /// The Id of the Poll
        /// </summary>
        private string PollID
        {
            get { return PollingWebPart.SPUserPollID; }
        }

        /// <summary>
        /// Thd ID of the WebPart
        /// </summary>
        private string WebPartID
        {
            get { return PollingWebPart.ID; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //set locale info for the enddate
            EndDate.LocaleId = (int)SPContext.Current.RegionalSettings.LocaleId;
            
            if (Page.IsPostBack == false)
            {
                DateTime zeroDate = new DateTime(2000, 1, 1, 1, 0, 0);

                //Only show unpublished screen if the poll has not been created
                if (PollingWebPart.SPUserPollCreationDate == zeroDate)
                {
                    phUnpublished.Visible = false;
                    phWelcome.Visible = true;
                }
                else
                {
                    phUnpublished.Visible = true;
                    phWelcome.Visible = false;

                    //request the available answers
                    StringBuilder availableAnswers = new StringBuilder();
                    DataTable answers = ManageLists.GetAnswersForPoll(PollID, false);
                    if (answers != null)
                    {
                        foreach (DataRow row in answers.Rows)
                        {
                            availableAnswers.Append(string.Format(" {0},", row["Title"].ToString()));
                        }
                        if (answers.Rows.Count > 0)
                        {
                            litAvailableAnswers.Text = string.Format("<strong>Configured answers:</strong>{0}<BR/><BR/>", availableAnswers.ToString().TrimEnd(",".ToCharArray()));
                        }
                    }
                }
            }
        }



        protected void lbCreatePoll_Click(object sender, EventArgs e)
        {
            //Validate the action!
            SPUtility.ValidateFormDigest();

            //check if the poll name is in use
            if (ManageLists.PollNameExists(txtPollTitle.Text))
            {
                litPollInUse.Text = "This title is already in use";
                return;
            }

            //Set webpart properties
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollQuestion", txtQuestion.Text);
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollTitle", txtPollTitle.Text);
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollResultType", Convert.ToInt32(dropdownResultType.SelectedValue));
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollResultDisplay", Convert.ToInt32(dropdownResultDisplay.SelectedValue));
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollCreationDate", DateTime.Now);
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollAllowMultipleAnswers", chkMultipleAnswers.Checked);
            ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollAnonymousVotes", chkAnonymous.Checked);
            
            //Set webpart enddate property
            if (Business.Components.DateAndTime.IsEndDateToday(EndDate.SelectedDate) == false)
                ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollClosingDate", EndDate.SelectedDate);
            else
                ManageWebParts.AlterWebPartProperty(Page.Request.Url.ToString(), WebPartID, "SPUserPollClosingDate", new DateTime(2000, 1, 1, 1,0,0));
            
            //save the settings
            ManageLists.AddOrUpdatePollRegistration(PollID, txtPollTitle.Text, txtQuestion.Text, SPContext.Current.Web.Title, false, HttpContext.Current.Request.Url.AbsolutePath.ToString());

            //create the default poll lists
            ManageLists.CreatePollLists(PollID, txtPollTitle.Text);            

            //reload the page to show the new web part title
            HttpContext.Current.Response.Redirect(Page.Request.Url.ToString());
 
        }

        /// <summary>
        /// Manage none label display option for charts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dropdownResultDisplay_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropdownResultDisplay.SelectedValue != "0")
            {
                if (dropdownResultType.Items.Count == 3)
                {
                    dropdownResultType.Items.Add(new ListItem("None", "3"));
                    dropdownResultType.SelectedItem.Selected = false;
                    dropdownResultType.Items[3].Selected = true;
                }
            }
            else
            {
                if (dropdownResultType.Items.Count > 3)
                {
                    dropdownResultType.SelectedItem.Selected = false;
                    dropdownResultType.Items.Remove(new ListItem("None", "3"));
                    dropdownResultType.Items[0].Selected = true;
                }
            }

        }
    }
}